package com.airena.controller;

import com.airena.entity.dto.UserLoginDTO;
import com.airena.entity.po.User;
import com.airena.entity.vo.UserLoginVo;
import com.airena.properties.JwtProperties;
import com.airena.result.Result;
import com.airena.service.IUserService;
import com.airena.utils.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


/**
 * 登录接口
 */
@RestController
@Slf4j
@Tag(name = "登录接口")
public class loginController {
    @Autowired
    private IUserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @Operation(summary = "用户登录接口")
    public Result<UserLoginVo> login(@ParameterObject UserLoginDTO userLoginDTO) {
            User user = userService.login(userLoginDTO);
            log.info("用户登录成功：用户名={}", user.getUsername());
            //登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();//存放员工id
            claims.put("id", user.getId());
            //创建jwt令牌
            String token = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims
            );

            UserLoginVo userLoginVo = UserLoginVo.builder()
                    .id(user.getId())
                    .userName(user.getUsername())
                    .name(user.getFullName())
                    .token(token)
                    .build();

            return Result.success(userLoginVo);
    }
}